#include "gkt_board.h"
#include "gkt_os.h"
#include "gkt_debug.h"
#include "gkt_cat_eye.h"

#if defined(GKT_CONFIG_CAT_EYE_ENABLE) && GKT_CONFIG_CAT_EYE_ENABLE \
	&& (GKT_MODULE_LOC_FRONTBOARD == GKT_CAT_EYE_LOCATION)

#ifndef GKT_CONFIG_CAT_EYE_ACTIVE_GPIO_PIN
#error "not define GKT_CONFIG_CAT_EYE_ACTIVE_GPIO_PIN"
#endif
#ifndef GKT_CONFIG_CAT_EYE_ACTIVE_LEVEL
#error "not define GKT_CONFIG_CAT_EYE_ACTIVE_LEVEL"
#endif

#define CAT_EYE_SYNC_TIMEOUT	100
#define CAT_EYE_ACTIVE_TIMEOUT_MS	1000

typedef struct {
	int	init_ok;
	gkt_cat_eye_status_e	status;
	gkt_mutex_t	mutex;
	gkt_soft_timer_t	timer_id;
	gkt_cet_eye_notify_fn	notify;
} cat_eye_fb_s;
static cat_eye_fb_s s_cat_eye_fb;

static void cat_eye_timer_callback(void)
{
	gkt_mutex_lock(s_cat_eye_fb.mutex, CAT_EYE_SYNC_TIMEOUT);
	if (GKT_CAT_EYE_ST_STARTING == s_cat_eye_fb.status) {
		s_cat_eye_fb.status = GKT_CAT_EYE_ST_ACTIVE;
		gkt_mutex_unlock(s_cat_eye_fb.mutex);

		if (s_cat_eye_fb.notify)
			(*s_cat_eye_fb.notify)(GKT_CAT_EYE_ST_ACTIVE);
	}
	else
		gkt_mutex_unlock(s_cat_eye_fb.mutex);
}

void gkt_cat_eye_register_notify(gkt_cet_eye_notify_fn notify)
{
	s_cat_eye_fb.notify = notify;
}

gkt_cat_eye_status_e gkt_cat_eye_get_status(void)
{
	return s_cat_eye_fb.status;
}

int gkt_cat_eye_start(void)
{
	int retval;

	gkt_info("cat_eye_start: <%d> status(%u)\n", 
		s_cat_eye_fb.init_ok, s_cat_eye_fb.status);

	if (!s_cat_eye_fb.init_ok)
		return GKT_ENOTINIT;

	gkt_mutex_lock(s_cat_eye_fb.mutex, 100);
	if (GKT_CAT_EYE_ST_ACTIVE == s_cat_eye_fb.status) {
		gkt_mutex_unlock(s_cat_eye_fb.mutex);
		return GKT_SUCCESS;
	}
	else if (GKT_CAT_EYE_ST_STARTING == s_cat_eye_fb.status) {
		gkt_mutex_unlock(s_cat_eye_fb.mutex);
		return GKT_EINPROCESS;
	}
	s_cat_eye_fb.status = GKT_CAT_EYE_ST_STARTING;
	gkt_mutex_unlock(s_cat_eye_fb.mutex);

	retval = gkt_gpio_set_pin_level(GKT_CONFIG_CAT_EYE_ACTIVE_GPIO_PIN, 
					GKT_CONFIG_CAT_EYE_ACTIVE_LEVEL);
	if (GKT_SUCCESS == retval) {
		retval = gkt_soft_timer_start(s_cat_eye_fb.timer_id, 
					CAT_EYE_ACTIVE_TIMEOUT_MS);
		if (GKT_SUCCESS == retval)
			retval = GKT_EINPROCESS;
		else 
	}
	else
		s_cat_eye_fb.status = GKT_CAT_EYE_ST_INACTIVE;

	return retval;
}

int gkt_cat_eye_init(void)
{
	int retval;

	s_cat_eye_fb.init_ok = 0;
	s_cat_eye_fb.status = GKT_CAT_EYE_ST_INACTIVE;
	s_cat_eye_fb.notify = NULL;

	retval = gkt_gpio_config(GKT_CONFIG_CAT_EYE_ACTIVE_GPIO_PIN);

	s_cat_eye_fb.mutex = gkt_mutex_create(0);
	if (!s_cat_eye_fb.mutex) {
		gkt_error("cat_eye: create mutex failed!\n");
		return GKT_ECREATE;
	}

	s_cat_eye_fb.timer_id = gkt_soft_timer_create(GKT_SOFT_TIMER_ONCE,
					cat_eye_timer_callback, NULL);
	if (!s_cat_eye_fb.timer_id) {
		gkt_error("cat_eye: create soft timer failed!\n");
		return GKT_ECREATE;
	}

	gkt_backboard_register_module(GKT_BB_MODULE_CAT_EYE,
			CAT_EYE_OP_MAX, cat_eye_module_notify);

	s_cat_eye_fb.init_ok = 1;
	
	return GKT_SUCCESS;
}

#endif


